<?php
namespace control;
/*
*周报记录类
*/
class weekRecordClass extends adIndexClass
{
    private const page = 'weekRecord';
    private const table = 'work_report';
    private const title = '周报';
    public array $stateOption = ['草稿', '待查看', '已查看'];
    public array $rateOption = ['优','良','中','差'];

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('report.table.week') => text(array("name" => "location", 'laydate' => ['type' => 'date', 'ready'=>'function(date){return onlyMonday()}', 'change' => 'function(date){return onlyMonday()}'])),
                    L('report.table.deptName')     => selectMultiple(["name" => "department", 'table' => " department", 'sqlId' => 'name', 'sqlField' => 'name', 'class' => 'width200']),
                    L('report.table.reportStid') => selectMultiple(["name" => "stid", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'class' => 'width200']),
                ],
                [
                    L('report.table.auditor')   => selectMultiple(["name" => "auditor", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'class' => 'width200']),
                    L('report.table.state') => select(array("name" => "state", "option" => $this->stateOption)),
                    L('report.table.grade')   => select(array("name" => "rate", "option" => $this->rateOption)),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        $button = "";
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'location'      => [
                        'name'  => L('report.table.weeks'),
                        'width' => 250,
                        'sort' => 1,
                    ],
                    'stid' => [
                        'name'  => L('report.table.reportStid'),
                        'width' => 250,
                    ],
                    'department'  => [
                        'name'  => L('report.table.deptName'),
                        'width' => 250,
                    ],
                    'auditor'         => [
                        'name'  => L('report.table.auditor'),
                        'width' => 250,
                    ],
                    'state'          => [
                        'name'  => L('report.table.state'),
                        'width' => 250,
                        'sort' => 1,
                    ],
                    'rate'    => [
                        'name'  => L('report.table.grade'),
                        'width' => 250,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = [
        ];
        //全等查询数组
        $equal = [
            "type"       => L('report.table.weekReport'),                      //
            "state"      => $this->post('state'),      //状态
            'auditor'    => $this->post('auditor'),    //审批人
            'stid'       => $this->post('stid'),       //汇报人
            'department' => $this->post('department')
        ];
        $and = " and state in ('待查看','已查看')";
        if ($this->post('location')) {
            $and .= $this->timeComparison($this->post('location'), 'month', 'location');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'location',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array("");
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "detail" => ["title" => L('report.table.weekInfo') . "", "click" => "newIframe('" . L('report.table.weekInfo') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')"],
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "location":
                        $row[] = self::formatDate($array['location'], 'Y年 - 第W周');
                        break;
                    case "stid":
                    case "auditor":
                        $row[] = self::findStaff($array[$key]);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 120),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }


    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = L('report.table.no_week');
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );
            $button = [];
            if ($info['auditor'] == self::$stid && $info['state'] == '待查看') {
                //按钮
                $button[] = [
                    "name" => L('report.table.audit'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'review', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            $commit = '<p>'.str_replace(['{{name}}'],[self::findStaff($info['stid'])],L('report.table.week_line_one')).'<span class="audit-record-time">'.$info['commitTime'].'</span></p>';
            if($info['state'] == '已查看'){
                $spanStr = '<span class="done">√</span>'.L('report.table.audit');
                $auditorTxt = '<p>'.str_replace(['{{name}}'],[self::findStaff($info['auditor'])],L('report.table.week_line_two')).'<span class="audit-record-time">'.$info['passTime'].'</span></p>';
            }else{
                $spanStr = '<span class="current">2</span>'.L('report.table.audit');
                $auditorTxt = '<p>'.str_replace(['{{name}}'],[self::findStaff($info['auditor'])],L('report.table.day_line_three')).'</p>';
            }
            $auditRecord  =<<<EOT
            <div class="audit-record">
            <ul class="audit-record-ul">
                <li>
                    <div class="left "><span class="done">√</span>发起</div>
                    <div class="right">{$commit}<div>
                </li>
                <li>
                    <div class="left">{$spanStr}</div>
                    <div class="right">{$auditorTxt}</div>
                </li>
            </ul>
        </div>
EOT;
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow([
                L('report.table.weekInfo')   => [
                    [
                        L('report.table.weeks') => self::formatDate($info['location'], 'Y年 - 第W周'),
                    ],
                    [
                        L('report.table.weekWork') => $info['now'],
                    ],
                    [
                        L('report.table.nextWeekWork') => $info['next'],
                    ],
                    [
                        L('report.table.otherMatter') => $info['other'],
                    ],
                ],
                L('report.table.systemInfo') => [
                    [
                        L('report.table.orderNo') => $info['orderNo'],
                        L('report.table.deptName') => $info['department'],
                        L('report.table.reportStid') => self::findStaff($info['stid']),
                    ],
                    [
                        L('report.table.auditor') => self::findStaff($info['auditor']),
                        L('report.table.time') => $info['time'],
                        L('report.table.reportTime') => $info['commitTime'],
                    ],
                    [
                        L('report.table.state') => $info['state'],
                        L('report.table.grade') => $info['rate'],
                    ],
                ],
                L('report.table.file')=>[
                    [
                        fileUploadClass::showFile($info['id'], self::title)
                    ],
                ],
                L('report.table.flow')=>[
                    [
                        $auditRecord
                    ]
                ]
            ]);

            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power =$msg= '';
        $append = [];
        $height = $word = false;
        switch ($act) {
            case 'review':
                $msg = '';
                $act = 'see';
                $word = true;
                $title = L('report.table.isCommit');
                $function = 'review';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                $append = [
                    [
                        must.L('report.table.opinion') => radio(['name'=>'state', 'value'=>[L('report.table.pass'), L('report.table.reject')]]).space
                    ],
                    [
                        L('report.table.grade') => radio(['name'=>'rate', 'value'=> $this->rateOption ])
                    ],
                    [
                        L('report.table.text') => textarea(['name'=>'text', 'class'=>'text width350'])
                    ]
                ];
                $height = 350;
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = $_SESSION['warn'] = str_replace(['{{msg}}'],[$msg],L('jon.other.permission_warn'));
            $json             = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title'    => $title,
                'function' => $function,
                'form'     => $form,
                'power'    => $power,
                'pwd'      => $pwd,
                'append'   => $append,
                'word'     => $word,
                'height'     => $height,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 修改状态
     *
     */
    public function review()
    {
        $array = $this->post('listId') ?? $this->post('id');
        $act = 'see';
        $json = [];
        if (!$this->power(self::page, $act)) {
            $json['warn'] = L('report.table.no_permission');
        } elseif (empty($array)) {
            $json['warn'] = L('report.table.no_data');
        } else {
            $text = '';
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            // 修改field
            $fieldKey = 'state';
            foreach ($array as $id) {
                $where = " id = '$id' ";
                $info = query(self::table, $where);
                if ($info['id']) {
                    if ($info['auditor'] != self::$stid) {
                        $text .= str_replace(['{{name}}','{{date}}','{{id}}'],[self::findStaff($info['stid']),$info['location'],$info['id']],L('report.table.week_audit_text')) . "<br>";
                        continue;
                    }
                    if ($info['state'] != '待查看') {
                        $text .=str_replace(['{{name}}','{{date}}','{{id}}'],[self::findStaff($info['stid']),$info['location'],$info['id']],L('report.table.week_audit_state')) . "<br>";
                        continue;
                    }
                    $fieldVlaue = ($this->post('state') == '通过') ? '已查看' : '草稿';
                    // 修改状态
                    static::update([
                        "table" => self::table,
                        'field' => [
                            $fieldKey  => $fieldVlaue,
                            'rate'     => $this->post('rate'),
                            'text'     => $this->post('text'),
                            'passTime' => $this->time,
                        ],
                        "where" => $where
                    ]);
                    //添加记录
                    $text .= str_replace(['{{staffName}}','{{name}}','{{date}}','{{id}}'],[$this->control['name'],self::findStaff($info['stid']),$info['location'],$info['id']],L('report.table.week_audit_log')) .'<br>';
                    $x++;
                }
            }
            // 写入日志
            $this->logText(["type" => self::page, "text" => $text]);
            $_SESSION['warn'] = str_replace(['{{x}}'],[$x],L('report.table.week_see_warn'));
            $json['warn']     = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        resp:
        return json_encode($json, 320);
    }
}
